package com.service.impl;

import com.dao.FunctionDAO;
import com.dao.UserDAO;
import com.dao.impl.FunctionDaoImpl;
import com.dao.impl.UserDaoImpl;
import com.entity.Function;
import com.entity.UserInfo;
import com.service.FunctionService;
import com.service.UserService;
import com.sys.utils.Mark;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 权限管理的业务逻辑类
 * 
 * @author xieqing
 * 
 */
public class FunctionServiceImpl implements FunctionService {

	private FunctionDAO dao = new FunctionDaoImpl();

	/**
	 * 添加用户信息
	 * 
	 * @param function
	 *            添加的信息
	 * @return
	 */
	public boolean add(Function function) {
		if (function != null && function.getName() != null
				&& function.getUrl() != null) {
			function.setMark(Integer.parseInt(Mark.DB_YES));
			return dao.add(function);
		}
		return false;
	}

	/**
	 * 修改权限信息
	 * 
	 * @param function
	 *            信息
	 * @return
	 */
	public boolean update(Function function) {
		if (function != null && function.getId() != null) {

			// 查询条件
			Function u1 = new Function();
			u1.setId(function.getId());

			List<Function> list = getList(u1);

			if (list != null && list.size() == 1) {
				Function pfunction = list.get(0);

				if (pfunction != null) {

					pfunction.setUrl(function.getUrl());
					pfunction.setId(function.getId());
					pfunction.setName(function.getName());
					pfunction.setMark(function.getMark());

					return dao.update(pfunction);
				}

			}

		}
		return false;
	}

	/**
	 * 删除用户信息
	 * 
	 * @param function
	 *            信息
	 * @return
	 */
	public boolean delete(Function function) {
		if (function != null && function.getId() != null) {

			List<Function> list = getList(function);

			if (list != null && list.size() == 1) {
				Function pfunction = list.get(0);

				if (pfunction != null) {

					pfunction.setMark(Integer.parseInt(Mark.DB_NO));
					return dao.update(pfunction);
				}

			}

		}
		return false;
	}

	/**
	 * 查询用户信息
	 * 
	 * @param function
	 *            查询条件
	 * @return
	 */
	public List<Function> getList(Function function) {

		StringBuilder sql = new StringBuilder(
				" SELECT a.* FROM function  a WHERE   a.mark=?");
		List<Object> list = new ArrayList<Object>();
		list.add(Mark.DB_YES);

		if (function != null) {

			if (function.getId() != null && !function.getId().equals("")) {
				sql.append(" and a.id=?");
				list.add(function.getId());
			}

			if (function.getName() != null
					&& !function.getName().equals("")) {
				sql.append(" and a.name like  ? ");
				list.add("%" +function.getName()+ "%");
			}

			if (function.getUrl() != null && !function.getUrl().equals("")) {
				sql.append(" and a.url like  ?  ");
				list.add("%" + function.getUrl() + "%");
			}



		}

		sql.append(" order by a.id desc");
		System.out.println(sql);
		return dao.getList(sql.toString(), list.toArray());
	}

	public List<Map> getCount() {
		return dao.getCount();
	}
}

